package com.xx.dome02;


import java.io.*;
import java.sql.*;

public class dome02 {


    String url = "jdbc:mysql://localhost:3306/zzy?characterEncoding=UTF-8";
    String driver = "com.mysql.jdbc.Driver";
    String user = "root";
    String password = "root";
    Connection connection = null;
    PreparedStatement preparedStatement= null;
    ResultSet resultSet = null;


    public void conDB(){
        try {
            Class.
                    forName(driver);
            connection = DriverManager.getConnection(url, user, password);
            System.out.println("成功向数据库插入文本");
        } catch(ClassNotFoundException e){
            e.printStackTrace();
        } catch (SQLException e ){
            e.printStackTrace();
        }
    }



    //写入到数据库
    public void writeDB(){
        String insertSql = "insert into zzy(context) value(?)";
        try {
            preparedStatement = connection.prepareStatement(insertSql);
            File file = new File("D:\\1.txt");
            FileReader fileReader = new FileReader(file);

            //使用setCharacterStream()设置字符流
            preparedStatement.setCharacterStream(1,fileReader,(int) file.length());
            preparedStatement.executeUpdate();
            System.out.println("成功插入文本");
        }catch (SQLException e){
            System.out.println("SQLException");
            e.printStackTrace();
        }catch (FileNotFoundException e){
            System.out.println("FileNotFoundException");
            e.printStackTrace();
        }
    }

    //读取
    public void redDB(){
        try {
            String selectSql = "select * from zzy where id = ?";
//            preparedStatement.setInt(1,1);
            preparedStatement.executeUpdate();
            resultSet = preparedStatement.getResultSet();
            if (resultSet.next()) {
                Reader reader = resultSet.getCharacterStream("context");
                //写入目标文件
                FileWriter fileWriter = new FileWriter(new File(
                        "D:\\file\\jdbc.txt"));
                char[] buffer = new char[1024];
                int len = 0;
                while ((len = reader.read(buffer)) != -1){
                    fileWriter.write(buffer,0 , len);
                }
                reader.close();
                fileWriter.close();
            }
        }catch (SQLException e){
            System.out.println("SQLException");
            e.printStackTrace();
        }catch (IOException e){
            System.out.println("IOException");
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        dome02 jdbcTest = new dome02();
        jdbcTest.conDB();
        jdbcTest.writeDB();
        jdbcTest.redDB();
        System.out.println("读取成功。。。");
    }

}
